package com.hcxny.chat

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.hcxny.chat.Constant.Companion.WS_URL
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import java.net.URI
import java.net.URLEncoder

class MainActivity : AppCompatActivity() {

    private lateinit var msgList: ArrayList<Msg>
    private lateinit var msgAdapter: MessageAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        initView()
        bind()
        init()
    }

    private fun initView() {
        msgList = arrayListOf(Msg("久chat", "kreedx"))
        msgAdapter = MessageAdapter(msgList)
        recycleView.adapter = msgAdapter
        recycleView.layoutManager = LinearLayoutManager(baseContext)
    }

    private var musicService: MusicService? = null

    private val connection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            val binder: MusicService.MyBinder = p1 as MusicService.MyBinder
            musicService = binder.getService()
        }


        override fun onServiceDisconnected(p0: ComponentName?) {

        }

    }

    @SuppressLint("WrongConstant")
    private fun bind() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, connection, 1)
    }

    private fun init() {
        CoroutineScope(Dispatchers.Main).launch {
            val token = Requester.chatService.login(LoginInfo("kree", "123456")).data.token
            val address = URLEncoder.encode("极寒之地", "UTF-8")

            val uri: URI =
                URI.create("${WS_URL}?token=${token}&address=${address}&EIO=4&transport=websocket")
            val client: JWebSocketClient = object : JWebSocketClient(uri) {
                override fun onMessage(message: String) {
                    //message就是接收到的消息
                    Log.e("JWebSClientService", message)
                    if (message.startsWith("2")) {
                        Log.e("JWebSClientService", "ping")
                        send("3")
                    }
                    if (message.startsWith("0")) {
                        Log.e("JWebSClientService", "online")
                        send("40")
                    }
                    if (message.startsWith("42")) {
                        val payload = message.substring(2)
                        val array = JSONArray(payload)
                        when (array[0]) {
                            "message" -> {
                                val data = array.getJSONObject(1)
                                val content =
                                    data.getJSONObject("data").getString("message_content")
                                val user = data.getJSONObject("data").getJSONObject("userInfo")
                                    .getString("user_nick")
                                msgList.add(Msg(content, user))
                                CoroutineScope(Dispatchers.Main).launch {
                                    msgAdapter.notifyDataSetChanged()
                                }

                            }
                            "switchMusic" -> {
                                val data = array.getJSONObject(1)
                                val musicSrc =
                                    data.getJSONObject("musicInfo").getString("music_src")
                                musicService?.play(MusicMsg(musicSrc, 0))
                            }
                            "initRoom" -> {
                                val data = array.getJSONObject(1)
                                val musicSrc = data.getString("music_src")
                                val startTime = data.getInt("music_start_time")
                                musicService?.play(MusicMsg(musicSrc, startTime))
                            }
                        }
                    }
                }
            }
            try {
                client.connect()
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }

//            Thread {
//                while (true){
//                    Thread.sleep(1000)
//                    if (client.isOpen) {
//                        Log.e("JWebSClientService", "ping")
//                        val byteArray = ByteArray(1)
//                        byteArray[0] = 40
////                        client.send("42[\"message\",{\"message_type\":\"text\",\"message_content\":\"1\"}]")
//                        client.sendPing()
//                    }
//                }
//            }.start()

            test.setOnClickListener {
                client.send("42[\"chooseMusic\",{\"music_mid\":199270536,\"music_duration\":283,\"music_album\":\"中国潮音 第1期\",\"music_artist\":\"裁缝铺&唐伯虎Annie&中国潮音\",\"music_albumpic\":\"https://img2.kuwo.cn/star/albumcover/500/25/98/4009041738.jpg\",\"music_pic120\":\"https://img2.kuwo.cn/star/albumcover/120/25/98/4009041738.jpg\",\"music_name\":\"新梅花三弄(Live)\",\"music_hasmv\":1}]")
                client.send("42[\"cutMusic\"]")
            }

            sendBtn.setOnClickListener {
                val text = contentEditor.text.toString()
                client.send("42[\"message\",{\"message_type\":\"text\",\"message_content\":\"${text}\"}]")
            }
        }
    }
}
